//
//  CreateJobInstallerPickUpRequiredView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/5/8.
//

import UIKit
import SnapKit
import RxGesture
import RxCocoa
import RxSwift
class CreateJobInstallerPickUpRequiredView: View {
    lazy var disposeBag = DisposeBag()
    var scrollToBottomClosure: (()->Void)?
    var scrollToAddAddressViewClosure: (()->Void)?
    var viewModel = CreateJobInstallerViewModel()
    let pickUpReqiredSwitchBtn = SwitchButton()
    let oswTypeLabel = OptionTypeLabel(DeliveryWarehouseType.OSW.rawValue.uppercased())
    let otherTypeLabel =  OptionTypeLabel(DeliveryWarehouseType.other.rawValue.capitalized)
    //开启pick up required后，则显示total back view，否则不显示
    let totalBackView = View()
    //共用pick up address和pick up reference
    lazy var pickUpAddressTextField: TextFieldWithRequiredView  = {
        let view = TextFieldWithRequiredView()
        view.textField.isEnabled = false
        view.textField.clearButtonMode = .never
        view.textField.showRightImageView("installation_list_search_down_arrow")
        return view
    }()
    lazy var pickupReferenceTextField: TextFieldWithRequiredView  = {
        let view = TextFieldWithRequiredView()
        view.needCheckFlag = false
        return view
    }()
    //
    //选择other，编辑地址
    let addressContent = View()
    var addAddressBtn: LayoutButton = {
        let view = LayoutButton(.left)
        view.setBtnInfo(R.string.localizable.addAddress(),hexStr: Constant.ThemeColorHexStr, textFont: R.font.interMedium(size: 14),imageName: "createjob_install_address_special_address_add")
        view.tag = 0
        return view
    }()
    lazy var addOtherAddressContent = View()
    lazy var editPhysicalAddress = PhysicalAddressView()
    
    let saveAddressBtn = OperationButton(R.string.localizable.saveAddress())
    var editPhysicalAddressValidFlag: Bool = true
    override func setUpView() {
        //switch
        self.addSubview(pickUpReqiredSwitchBtn)
        pickUpReqiredSwitchBtn.snp.makeConstraints { make in
            make.top.equalTo(Constant.TopBottomMargin)
            make.right.equalToSuperview()
            make.size.equalTo(SwitchButton.size)
        }
        //pickUpRequired title
        let pickUpRequiredTitle = ContentLabel()
        pickUpRequiredTitle.numberOfLines = 0
        pickUpRequiredTitle.lineBreakMode = .byWordWrapping
        pickUpRequiredTitle.text = R.string.localizable.needTheInstallerToPickUpTheOrder()
        self.addSubview(pickUpRequiredTitle)
        pickUpRequiredTitle.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.lessThanOrEqualTo(pickUpReqiredSwitchBtn.snp.left)
            make.height.width.greaterThanOrEqualTo(0)
            make.centerY.equalTo(pickUpReqiredSwitchBtn)
        }
        
        //****整个开启pick up required后的内容都在里边
        self.addSubview(totalBackView)
        totalBackView.snp.makeConstraints { make in
            make.top.equalTo(pickUpReqiredSwitchBtn.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        
        self.initBiding()
    }
    //MARK: - 数据绑定
    func initBiding(){
        //切换pick up required，是否显示下边的pick up address 信息
        pickUpReqiredSwitchBtn.rx.observe(Int.self, "tag").subscribe {[weak self] (btnTag) in
            guard let strongSelf = self, let tag = btnTag else {return }
            if tag == 1{//开启pick up required
                strongSelf.showPickupRequiredView()
                strongSelf.viewModel.pickupRequired = true
                strongSelf.scrollToBottomClosure?()//滚动到pick up address方便客户增加新地址
            }else{//关闭
                strongSelf.delPickupRequiredView()
                strongSelf.viewModel.pickupRequired = false
                strongSelf.viewModel.address_type = .none
                strongSelf.viewModel.delivery_address_id = 0
                strongSelf.viewModel.delivery_address_text = ""
                strongSelf.viewModel.pickupReference = ""
            }
        }.disposed(by: self.disposeBag)
        //选择osw
        oswTypeLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击osw，不做处理
            if self?.viewModel.address_type == .OSW { return }
            self?.changeAddressType(.OSW)
            self?.scrollToBottomClosure?()//滚动到pick up address方便客户增加新地址
        }).disposed(by: self.disposeBag)
        //选择other
        otherTypeLabel.rx.tapGesture().when(.recognized).subscribe (onNext: { [weak self] _ in
            //重复点击other，不做处理
            if self?.viewModel.address_type == .other { return }
            self?.changeAddressType(.other)
            self?.scrollToBottomClosure?()//滚动到pick up address方便客户增加新地址
        }).disposed(by: self.disposeBag)
        //
        //监听pickup address编辑内容
        pickUpAddressTextField.rx.tapGesture().when(.recognized).subscribe(onNext: {[weak self] _ in
            guard let strongSelf = self else {return}
            strongSelf.selectDeliveryWarehouse()
        }).disposed(by: self.disposeBag)
        //监听pickupReference编辑内容
        pickupReferenceTextField.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.pickupReference = data
        }
        //
        saveAddressBtn.rx.tap.subscribe { [weak self] _ in
            guard let strongSelf = self else {return}
            strongSelf.editPhysicalAddress.validateAllRequiredFieldWhenEdit()
            if strongSelf.editPhysicalAddress.everythingValidFlag {
                strongSelf.saveDeliveryWarehouse(strongSelf.editPhysicalAddress.addressModel)
            }
        }.disposed(by: self.disposeBag)
        pickupReferenceTextField.textField.placeholder = R.string.localizable.pleaseEnterPickUpReferenceNumber()
        addAddressBtn.addTarget(self, action: #selector(addAddressBtnClick(_:)), for: UIControl.Event.touchUpInside)
    }
    func setData(_ viewModel: CreateJobInstallerViewModel ){
        self.viewModel = viewModel
        self.pickUpReqiredSwitchBtn.switchOn(self.viewModel.pickupRequired)
        self.changeAddressType(self.viewModel.address_type)
    }
    //MARK: - 关闭pick up required，删除下边的内容view
    private func delPickupRequiredView(){
        //隐藏add address
        if self.addAddressBtn.tag == 1{
            self.addAddressBtnClick(self.addAddressBtn)
        }
        //remove all subviews
        for subview in self.addressContent.subviews{
            subview.removeFromSuperview()
        }
        //remove all subviews
        for subview in self.totalBackView.subviews{
            subview.removeFromSuperview()
        }
        //清空数据
        oswTypeLabel.setUnSelect()
        otherTypeLabel.setUnSelect()
        pickUpAddressTextField.textField.text = ""
        pickupReferenceTextField.textField.text = ""
    }
    //MARK: - 开启pick up required，增加下边的内容view
    private func showPickupRequiredView(){
        //pickUp address title
        let pickUpAddresTitle = LabelWithRedStarView(R.string.localizable.pickUpAddress())
        totalBackView.addSubview(pickUpAddresTitle)
        pickUpAddresTitle.snp.makeConstraints { make in
            make.top.left.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //oswTypeLabel
        totalBackView.addSubview(oswTypeLabel)
        oswTypeLabel.snp.makeConstraints { (make) in
            make.top.equalTo(pickUpAddresTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //otherTypeLabel
        totalBackView.addSubview(otherTypeLabel)
        otherTypeLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(oswTypeLabel)
            make.left.equalTo(oswTypeLabel.snp.right).offset(Constant.InternalMargin)
            make.right.equalToSuperview()
            make.height.width.equalTo(oswTypeLabel)
        }
        //
        addressContent.backgroundColor = .white
        totalBackView.addSubview(addressContent)
        addressContent.snp.makeConstraints { (make) in
            make.top.equalTo(oswTypeLabel.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
    }
    //MARK: - 选择osw或other的仓库地址
    private func selectDeliveryWarehouse(){
        Tool().showSearchDeliveryListView(deliveryWarehouseType: self.viewModel.address_type) {[weak self] (result) in
            guard let strongSelf = self else { return}
            strongSelf.setDeliverWarehouseInfo(result)
        }
    }
    
    //MARK: - 此方法两个地方用，一个地方是选择address，一个地方是other创建新的address后自动赋值
    func setDeliverWarehouseInfo(_ model: DeliveryWarehouseModel){
        self.viewModel.delivery_address_id = model.id
        self.viewModel.delivery_address_text = model.address_text
        self.pickUpAddressTextField.textField.text = model.address_text
    }
    @objc func addAddressBtnClick(_ sender: LayoutButton){
        if sender.tag == 0{//增加special address
            self.addOtherPickUpAddress()
            self.scrollToAddAddressViewClosure?()//滚动到地址
        }else{//删除special address
            self.delOtherPickUpAddress()
        }
    }
    //MARK: - 增加other pickup status UI
    private func addOtherPickUpAddress(){
        addAddressBtn.setBtnInfo(R.string.localizable.cancel(),hexStr: "#DD890B", textFont: R.font.interMedium(size: 14),imageName: "createjob_install_address_special_address_del")
        addAddressBtn.tag = 1
        self.addOtherAddressView()
    }
    //MARK: - 删除other pickup status UI
    func delOtherPickUpAddress(){
        addAddressBtn.setBtnInfo(R.string.localizable.addAddress(),hexStr: Constant.ThemeColorHexStr, textFont: R.font.interMedium(size: 14),imageName: "createjob_install_address_special_address_add")
        addAddressBtn.tag = 0
        self.delOtherAddressView()
        
    }
    //MARK: - 选择pick up地址类型
    private func changeAddressType(_ addressType: DeliveryWarehouseType){
        if addressType == .none {return}
        //remove all subviews
        for subview in self.addressContent.subviews{
            subview.removeFromSuperview()
        }
        if addressType == .OSW {//OSW
            self.oswTypeLabel.setSelect()
            self.otherTypeLabel.setUnSelect()
            self.initUIByOSW()
            
        }else {// other
            self.oswTypeLabel.setUnSelect()
            self.otherTypeLabel.setSelect()
            self.initUIByOther()
        }
        self.viewModel.address_type = addressType
        self.viewModel.delivery_address_id = 0
        self.viewModel.delivery_address_text = ""
        self.pickUpAddressTextField.textField.text = ""//切换地址后要清空pickup address
    }
    //MARK: - 初始化OSW的UI
    func initUIByOSW(){
        //pick up address
        pickUpAddressTextField.textField.placeholder = R.string.localizable.selectOSWWarehouseAddress()
        self.addressContent.addSubview(pickUpAddressTextField)
        pickUpAddressTextField.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //共用：pick up reference
        let pickupReferenceTitle = ContentLabel()
        pickupReferenceTitle.text = R.string.localizable.pickUpReference()
        self.addressContent.addSubview(pickupReferenceTitle)
        pickupReferenceTitle.snp.makeConstraints { make in
            make.top.equalTo(pickUpAddressTextField.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //
        self.addressContent.addSubview(pickupReferenceTextField)
        pickupReferenceTextField.snp.makeConstraints { make in
            make.top.equalTo(pickupReferenceTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalToSuperview()
            make.height.equalTo(DIYTextField.height)
            make.bottom.equalToSuperview()
        }
    }
    //MARK: - 初始化ohter的UI
    func initUIByOther(){
        pickUpAddressTextField.textField.isEnabled = false//不可编辑，调用接口搜索查找
        pickUpAddressTextField.textField.placeholder = R.string.localizable.selectPickUpAddress()
        self.addressContent.addSubview(pickUpAddressTextField)
        pickUpAddressTextField.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //
        self.addressContent.addSubview(addAddressBtn)
        addAddressBtn.snp.makeConstraints { make in
            make.top.equalTo(pickUpAddressTextField.snp.bottom)
            make.left.equalToSuperview()
            make.width.greaterThanOrEqualTo(0)
            make.height.equalTo(40)
        }
        self.addressContent.addSubview(addOtherAddressContent)
        addOtherAddressContent.snp.makeConstraints { make in
            make.top.equalTo(addAddressBtn.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //
        //共用：pick up reference
        let pickupReferenceTitle = ContentLabel()
        pickupReferenceTitle.text = R.string.localizable.pickUpReference()
        self.addressContent.addSubview(pickupReferenceTitle)
        pickupReferenceTitle.snp.makeConstraints { make in
            make.top.equalTo(addOtherAddressContent.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //
        self.addressContent.addSubview(pickupReferenceTextField)
        pickupReferenceTextField.snp.makeConstraints { make in
            make.top.equalTo(pickupReferenceTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalToSuperview()
            make.height.equalTo(DIYTextField.height)
            make.bottom.equalToSuperview()
        }
    }
    
    //MARK: - 点击Add address，显示增加地址的view
    private func addOtherAddressView(){
        //点击增加地址的时候，隐藏pickUpAddressTextField,
        pickUpAddressTextField.isHidden = true
        self.addAddressBtn.snp.remakeConstraints { make in
            make.top.left.equalToSuperview()
            make.width.greaterThanOrEqualTo(0)
            make.height.equalTo(40)
        }
        //title
        let addressLabel = ContentLabel()
        addressLabel.text = R.string.localizable.address()
        self.addOtherAddressContent.addSubview(addressLabel)
        addressLabel.snp.makeConstraints { make in
            make.top.equalTo(Constant.TopBottomMargin)
            make.left.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //创新选择address type时，重置内容
        self.addOtherAddressContent.addSubview(editPhysicalAddress)
        editPhysicalAddress.snp.makeConstraints { make in
            make.top.equalTo(addressLabel.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //
        saveAddressBtn.backgroundColor = UIColor(hexStr: "#70798A")
        self.addOtherAddressContent.addSubview(saveAddressBtn)
        saveAddressBtn.snp.makeConstraints { make in
            make.top.equalTo(editPhysicalAddress.snp.bottom).offset(Constant.AllOutMargin)
            make.centerX.equalToSuperview()
            make.width.equalTo(200)
            make.height.equalTo(OperationButton.height)
            make.bottom.equalToSuperview()
        }
    }
    //MARK: - 点击Remove address，删除增加地址的view
    private func delOtherAddressView(){
        //点击删除地址的时候，显示pickUpAddressTextField,
        pickUpAddressTextField.isHidden = false
        addAddressBtn.snp.remakeConstraints { make in
            make.top.equalTo(pickUpAddressTextField.snp.bottom).offset(12)
            make.left.equalToSuperview()
            make.width.greaterThanOrEqualTo(0)
            make.height.equalTo(40)
        }
        //remove all subviews
        for subview in self.addOtherAddressContent.subviews{
            subview.removeFromSuperview()
        }
    }
    //MARK: - other创建当前company id下的warehouse
    private func saveDeliveryWarehouse(_ addressModel: PhysicalAddressViewModel){
        let service = DictionaryService()
        service.setBlockAfterNetwork { [weak self] (result, otherInfo) in
            ModelViewUtil.shared.hideLoadingView()
            guard let strongSelf = self else {return}
            if let list = result as? Array<DeliveryWarehouseModel>{
                if let newModel = list.first(where: {$0.address_text == addressModel.final_full_address}){
                    strongSelf.setDeliverWarehouseInfo(newModel)
                    strongSelf.delOtherPickUpAddress()
                }
            }
                
        } errorBlock: { code, error in
            ModelViewUtil.shared.hideLoadingView()
            Tool().showErrorInfo(code,error)
        }
        ModelViewUtil.shared.showLoadingView("Creating...")
        service.createDeliveryWarehouse(addressModel: addressModel, companyID: CreateJobModelHelper.shared.createJobViewModel.summaryViewModel.company_id)
    }
}
